<!-- 新增或编辑
{
  "sche_guid": "sample string 1",
  "schemeName": "sample string 2",
  "defaultPrice": 3.0,
  "eqType": "sample string 4",
  "useType": "sample string 5",
  "timeInterval": "sample string 6",
  "loss": 7.0
} 
-->
 <template>
    <div>
        <Form ref="formValidate1" :model="formValidate" :rules="ruleValidate" :label-width="140">
            <Tabs :model-value="sbType">
                <TabPane label="基本方案" name="wg">
                    <FormItem label="方案名称" prop="schemeName">
                        <Input v-model="formValidate.schemeName" placeholder="请输入方案名称"></Input>
                    </FormItem>

                    <FormItem label="默认价格" prop="defaultPrice">
                        <Input v-model="formValidate.defaultPrice" placeholder="请输入默认价格"></Input>
                    </FormItem>

                    <FormItem label="能耗类型" prop="eqType">
                        <Select v-model="formValidate.eqType" placeholder="请选择能耗类型" @on-change="changeType">
                            <Option :value="item.value" v-for="item in typeCodeList" v-bind:key="item.value">{{ item.label }}</Option>
                        </Select>
                    </FormItem>

                    <FormItem label="分项类型" prop="usetype">
                        <Select v-model="formValidate.usetype" placeholder="请选择分项类型">
                            <Option :value="item.value" v-for="item in typeList" v-bind:key="item.value">{{ item.label }}</Option>
                        </Select>
                    </FormItem>

                    <FormItem label="线损率" prop="loss">
                        <Input min="0" max="100" type="number" v-model="formValidate.loss" placeholder="请输入线损率">
                            <!-- prepend 前置 -->
                            <!-- append 后置 -->
                            <label slot="append"> %</label>
                        </Input>
                    </FormItem>
                </TabPane>

                <TabPane label="时段方案" name="zd">
                    <div>
                        <custom-button title="添加时段" type="add" style="margin-right: 10px" @addClick="addClick"></custom-button>
                    </div>
                    <div style="padding: 10px 0">
                        <table-index
                            :dataSource="dataSource"
                            :tableColumns="tableColumns"
                            :btnList="btnList"
                            @deleteRow="deleteRow"
                            :showPage="false"
                            :height="350"
                        ></table-index>
                    </div>
                </TabPane>
            </Tabs>
            <FormItem>
                <Button type="primary" @click="handleSubmit('formValidate1')">提交</Button>
                <!-- <Button @click="handleReset('formValidate')" style="margin-left: 8px">Reset</Button> -->
            </FormItem>
        </Form>

        <div v-if="dialogShow">
            <custom-dialog :zIndex="10" :title="dialogTitle" size="tiny" @dialogClose="dialogShow = false">
                <Form ref="formValidate2" :model="formValidate2" :rules="ruleValidate2" :label-width="140">
                    <FormItem label="时段名" prop="name">
                        <Input v-model="formValidate2.name" placeholder="请输入时段名"></Input>
                    </FormItem>

                    <FormItem label="开始时间" prop="starttime">
                        <TimePicker
                            type="time"
                            placeholder="请选择开始时间"
                            format="HH:mm"
                            v-model="formValidate.starttime"
                            @on-change="
                                (e) => {
                                    changeTime(e, 's')
                                }
                            "
                        ></TimePicker>
                    </FormItem>
                    <FormItem label="结束时间" prop="endtime">
                        <TimePicker
                            type="time"
                            placeholder="请选择结束时间"
                            format="HH:mm"
                            v-model="formValidate.endtime"
                            @on-change="
                                (e) => {
                                    changeTime(e, 'e')
                                }
                            "
                        ></TimePicker>
                    </FormItem>

                    <FormItem label="价格" prop="price">
                        <Input type="number" v-model="formValidate2.price" placeholder="请输入价格"></Input>
                    </FormItem>
                    <FormItem>
                        <Button type="primary" @click="handleSubmit('formValidate2')">提交</Button>
                    </FormItem>
                </Form>
            </custom-dialog>
        </div>
    </div>
</template>



<script>
import {AjaxCommon} from '@/libs/apiCommon'
import {PopupCommon} from '@/libs/popupCommon'
import tableIndex from '@/components/customComponents/customeTable/iviewTable/singleViewTable'
import {Utility, IconNames} from '@/libs/utility'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import customButton from '@/components/customComponents/customForm/customButton'
import customDialog from '@/components/customComponents/customDialog'

export default {
    props: ['setData', 'type'],
    components: {Treeselect, customButton, tableIndex, customDialog},
    data() {
        return {
            // 弹窗是否显示
            dialogShow: false,
            // 弹窗标题 (新增修改不同)
            dialogTitle: '新增时段',
            sbType: 'wg',
            typeCodeList: [],
            typeList: [],
            itemMenu: {},
            showIcon: false,
            iconList: [],
            value: null,
            options: [],
            // 采集ip
            cjIpList: [],
            // 采集端口
            cjDkList: [],
            formValidate2: {
                name: '',
                starttime: '',
                endtime: '',
                price: ''
            },
            formValidate: {
                sche_guid: '',
                schemeName: '',
                defaultPrice: '',
                eqType: '',
                usetype: '',
                loss: 0,
                timeInterval: ''
            },
            ruleValidate2: {
                name: [{required: true, message: '请输入时段名', trigger: 'blur'}],
                starttime: [{required: true, type: 'string', message: '请选择开始时间', trigger: 'blur'}],
                endtime: [{required: true, type: 'string', message: '请选择结束时间', trigger: 'blur'}],
                price: [{required: true, message: '请填写价格', trigger: 'blur'}]
            },
            ruleValidate: {
                // trigger 不要传数组，否则会导致验证结果一直为true
                schemeName: [{required: true, message: '请输入方案名称', trigger: 'blur'}],
                defaultPrice: [{required: true, message: '请输入默认价格', trigger: 'blur'}],
                eqType: [{required: true, message: '请选择能耗类型', trigger: 'change'}],
                usetype: [{required: true, message: '请选择分项类型', trigger: 'change'}]
                // loss: [{required: true, message: '请输入折损率', trigger: 'blur', min: 0, max: 100}]
            },

            // table 相关参数  begin
            dataSource: [],
            tableColumns: [
                {
                    key: 'name',
                    title: '时段名',
                    tree: true
                },
                {
                    key: 'starttime',
                    title: '开始时间'
                },
                {
                    key: 'endtime',
                    title: '结束时间'
                },

                {
                    key: 'price',
                    title: '价格'
                },
                {
                    title: '操作',
                    slot: 'action',
                    width: 120,
                    align: 'center'
                }
            ],
            btnList: ['delete']
            // table 相关参数  end
        }
    },
    methods: {
        changeTime(t, v) {
            if (v == 's') {
                this.formValidate2.starttime = t
            } else {
                this.formValidate2.endtime = t
            }
        },
        deleteRow(item) {
            const index = item._index
            this.dataSource.splice(index, 1)
        },
        initPage() {},
        addClick() {
            this.dialogShow = true
        },
        handleSubmit(name) {
            const self = this
            this.$refs[name].validate((valid) => {
                if (valid) {
                    if (name == 'formValidate2') {
                        const data = self.dataSource
                        data.push({
                            name: self.formValidate2.name,
                            starttime: self.formValidate2.starttime,
                            endtime: self.formValidate2.endtime,
                            price: self.formValidate2.price
                        })
                        self.dataSource = data
                        self.dialogShow = false
                    } else {
                        let timeInterval = ''
                        if (self.dataSource && self.dataSource.length > 0) {
                            // timeInterval  时段方案字符串：上午|06:00|12:00|0.580,中午|12:00|14:00|0.560
                            self.dataSource.forEach((t) => {
                                timeInterval += `${t.name}|${t.starttime}|${t.endtime}|${t.price},`
                            })
                        }
                        if (timeInterval) {
                            timeInterval = timeInterval.substring(0, timeInterval.length - 1)
                        }
                        self.formValidate.timeInterval = timeInterval
                        self.$emit('getData', self.formValidate)
                    }
                }
            })
        },
        changeType(item) {
            this.getChildDict(item)
        },
        async getChildDict(item) {
            const res = await AjaxCommon(`/api/Eq/GetUseTypeByEqType/${item}`, 'get', null)
            let newData = []
            const data = res.data?.Message ?? []
            data?.map((t) => {
                newData.push({
                    value: t.DIC_VALUE,
                    label: t.DIC_DESC
                })
            })

            this.typeList = newData
        },
        async initData() {
            // 能耗类型
            const res = await AjaxCommon('/api/Eq/GetEqTypeDataDics', 'get', null)
            let newData = []
            const data1 = res.data?.Message ?? {}
            data1.energy.map((t) => {
                newData.push({
                    value: t.dic_value,
                    label: t.dic_desc
                })
            })
            this.typeCodeList = newData
            // 编辑 或 新增子级
            if (this.setData && this.type == 'edit') {
                const d = this.setData
                // 这里是真坑，返回title出来，存又是存的value
                const eqType = this.typeCodeList.find((t) => t.label == d.eqType)?.value
                this.setData.eqType = eqType
                await this.getChildDict(this.setData.eqType)
                const usetype = this.typeList.find((t) => t.label == d.usetype)?.value
                this.setData.usetype = usetype
                this.formValidate = this.setData
            }

            const data = this.setData

            // 价格时段设置
            if (data?.sche_guid) {
                // api/Eq/GetPriceSchemeInfo?sche_guid={sche_guid}
                const params = `/api/Eq/GetPriceSchemeInfo?sche_guid=${data?.sche_guid}`
                AjaxCommon(params, 'get', null).then((res) => {
                    console.log(res)
                    // 价格时段
                    const timeInterval = res.data.Message?.timeInterval ?? []
                    this.dataSource = timeInterval?.map((t) => {
                        return {
                            name: t.timeName,
                            starttime: t.startTime,
                            endtime: t.endTime,
                            price: t.price
                        }
                    })
                })
            }
        }
    },
    created() {
        if (this.type == 'add') {
            this.formValidate = {
                sche_guid: '',
                schemeName: '',
                defaultPrice: '',
                eqType: '',
                usetype: '',
                loss: 0,
                timeInterval: ''
            }
        }
        this.initData()
    },
    mounted() {
        this.$nextTick(() => {})
    }
}
</script>

<style lang="scss">
.selectIcon {
    position: absolute;
    top: 0px;
    left: 0;
    width: 100%;
    height: 156px;
    z-index: 999999;
    border: 1px solid #e0e0e0;
    background: #fff;
    border-radius: 4px;
    padding: 4px;
    overflow-y: auto;
    overflow-x: hidden;
    .bi {
        margin-right: 10px;
        margin-bottom: 10px;
        cursor: pointer;
    }
}
</style>
